<template>
  <div class="collection-result">
    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">{{ modelName }}</span>
        <div>
          <el-button type="primary" size="small" @click="addNewData"
            >新增</el-button
          >
          <el-button type="primary" size="small" @click="downloadModel"
            >导出模板</el-button
          >
          <el-upload
            class="upload-demo"
            :action="`${this.$api.dataCollection.uploadModelData}`"
            multiple
            :show-file-list="false"
            :data="fileParam"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvataError"
          >
            <el-button size="small" type="primary">导入</el-button>
          </el-upload>
          <el-button type="primary" size="small" @click="download"
            >导出</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableList"
        :cell-style="{ color: '#333333' }"
        :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
      >
        <el-table-column
          type="index"
          label="ID"
          width="50"
          align="center"
          fixed="left"
        ></el-table-column>
        <el-table-column label="操作" fixed="left" align="center">
          <template slot-scope="scope" class="test">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              v-if="scope.row.isEdit"
              @click.native.prevent="save(scope.row)"
              >保存</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="edit(scope.row)"
              v-else
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              v-if="scope.row.isNew"
              @click.native.prevent="deleteData(scope.row)"
              >删除</el-link
            >
          </template>
        </el-table-column>
        <el-table-column
          v-for="item in tableTitle"
          :key="`${item[0]}`"
          :label="item[1]"
          show-overflow-tooltip
          align="left"
        >
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row[item[0]]"
              size="small"
              :class="
                scope.row.errorList && scope.row.errorList[item[0]]
                  ? 'error'
                  : ''
              "
            ></el-input>
            <span class="visit-cell" v-else>{{ scope.row[item[0]] }}</span>
            <div
              v-if="scope.row.errorList && scope.row.errorList[item[0]]"
              class="error-hint"
            >
              {{ scope.row.errorList[item[0]] }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        small
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="modelData.pageSize"
        :pager-count="7"
        :current-page="modelData.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
export default {
  name: "DataDetail",
  data: () => {
    return {
      modelName: null,
      modelData: {
        modelId: "", // 数据模型id
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      tableList: [], // 采集任务列表
      total: 0, // 数据总条数
      loading: false,
      dialogFormVisible1: false,
      fieldList: [], // 所有字段
      tableTitle: [], // [[key,中文标题],]排除 不展示的key
      filterKeys: new Set(["id"]), // 列表不展示的key
      fileModel: {
        file_url: "",
      },
      fileParam: {
        modelId: null,
      },
    };
  },
  created() {
    this.modelData.modelId = this.$route.params.id;
    this.fileParam.modelId = this.modelData.modelId;
    this.getDataMaintenanceDetail();
  },
  methods: {
    // 获取采集任务列表
    getDataMaintenanceDetail() {
      const params = this.modelData;
      this.$axios
        .post(this.$api.dataCollection.getDataMaintenanceDetail, params)
        .then((res) => {
          let { code, message, data } = res.data;
          if (code !== 200) {
            this.$message.warning(message);
            return;
          }
          this.modelName = data.modelName;
          this.total = +data.totalCount;
          this.modelData.pageNum = +data.pageNum;
          this.tableList = [];
          this.tableTitle = [];
          this.fieldList = [];
          this.tableList = this.transferTableList(data.dataList);
          this.tableTitle = this.filterTableTitleList(data.fieldList);
          this.$utils.backtop(this.containerDom);
          // console.log("tableTitle", this.tableTitle);
          // console.log("tableList", this.tableList);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    filterTableTitleList(_fieldList) {
      _fieldList.forEach((item) => {
        let fieldItem = Object.entries(item)[0];
        this.fieldList.push(fieldItem);
      });
      let needShowFielList = [];
      this.fieldList.forEach((item) => {
        if (!this.filterKeys.has(item[0])) {
          needShowFielList.push(item);
        }
      });
      return needShowFielList;
    },
    transferTableList(_dataList) {
      let dataList = _dataList.map((item) => {
        item.isEdit = false;
        item.hasError = false;
        item.uuid = this.$utils.uuid();
        item.errorList = {};
        return item;
      });
      return dataList;
    },
    // 查询
    onSubmit(pageNum) {
      this.modelData.pageNum = pageNum ? pageNum : this.modelData.pageNum;
      this.getDataMaintenanceDetail();
    },
    // 修改当前页码
    handleCurrentChange(page) {
      this.modelData.pageNum = page;
      this.getDataMaintenanceDetail();
    },
    // 修改每页条数
    handleSizeChange(e) {
      this.modelData.pageSize = e;
      this.getDataMaintenanceDetail();
    },
    closeDialog() {
      this.dialogFormVisible1 = false;
    },
    // 新增
    addNewData() {
      let newData = { isEdit: true, isNew: true, errorList: {} };
      this.tableTitle.forEach((item) => {
        let key = item[0];
        newData[key] = "";
      });
      this.filterKeys.forEach((key) => {
        newData[key] = null;
      });
      this.tableList.unshift(newData);
    },
    // 下载模板
    downloadModel() {
      this.$axios({
        url: `${this.$api.dataCollection.exportTemplateOfModelData}?modelId=${this.modelData.modelId}`,
        method: "get",
        responseType: "blob",
      })
        .then((res) => {
          let url = window.URL.createObjectURL(new Blob([res.data]), {
            type: "charset=utf-8",
          });
          var a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          a.download = `${this.modelName}数据导入模板.xlsx`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 导入成功的回调
    handleAvatarSuccess(res, file) {
      this.$message.success("导入成功");
      this.modelData.pageNum = 1;
      this.getDataMaintenanceDetail();
    },
    handleAvataError(res) {
      this.$message.warning(res.message);
    },
    // 导出
    download() {
      this.$axios({
        url: `${this.$api.dataCollection.exportModelData}?modelId=${this.modelData.modelId}`,
        responseType: "blob",
        methods: "get",
      })
        .then((res) => {
          let url = window.URL.createObjectURL(new Blob([res.data]), {
            type: "charset=utf-8",
          });
          var a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          a.download = `${this.modelName}.xlsx`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 编辑
    edit(row) {
      row.isEdit = true;
    },
    // 保存
    save(row) {
      let _params = {};
      this.fieldList.forEach((item) => {
        let field = item[0];
        _params[field] = row[field];
      });
      let params = { ..._params, modelId: this.modelData.modelId };
      this.$axios
        .post(this.$api.dataCollection.saveModelData, params)
        .then((res) => {
          let { code, message, data } = res.data;
          console.log("res", res.data);
          if (code === 200) {
            row.isNew = false;
            row.isEdit = false;
            row.hasError = false;
            row.errorList = {};
            return;
          }
          // 标出每个字端错误日志
          if (code === 666) {
            console.log("666");
            console.log("row", row);
            row.errorList = {};
            let { field, logDetail } = data;
            row.hasError = true;
            row.errorList[field] = logDetail;
            let updateIndex;
            if (row.isNew) {
              updateIndex = 0;
            } else {
              updateIndex = this.tableList.findIndex((item) => {
                return item.id === row.id;
              });
            }
            console.log("updateIndex", updateIndex);
            this.tableList.splice(updateIndex, 1, row);
            return;
          }
          // 无法逐个标出的错误用弹框表示
          this.$message.warning(message);
        });
    },
    getError(key) {
      return this.errorList[key];
    },
    // 删除 只允许删除新增未保存成功的
    deleteData() {
      this.tableList.shift();
    },
  },
};
</script>
<style lang="scss" scoped>
.collection-result {
  position: relative;

  .cate-head {
    display: flex;

    .cate-right {
      #btn {
        margin-right: -10px;
      }
    }
  }

  .search-form {
    padding: 16px 32px;
    border-radius: 4px;
    background: #ffffff;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      /deep/ .el-input__inner {
        width: 240px;
        height: 32px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #e0e0e0;
      }
    }
  }

  .el-select {
    /deep/ .el-input__inner {
      width: 240px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #e0e0e0;
    }
  }

  .server-table {
    // margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }
      .el-button {
        margin-left: 10px;
      }
      margin-bottom: 10px;
    }

    .little-circle-blue {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #55c898;
      position: relative;
      right: 4px;
      top: -2px;
    }

    .little-circle-red {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #ee5564;
      position: relative;
      right: 6px;
      top: -2px;
    }

    .page-wrapper {
      margin-top: 28px;
      display: flex;
      justify-content: flex-end;
      color: rgba(0, 0, 0, 0.65);

      .data-counter {
        font-weight: 400;
        line-height: 32px;
        margin-right: 24px;
      }

      /deep/ .btn-prev,
      /deep/ .btn-next {
        margin: 0 4px;
        min-width: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        padding: 0;
      }

      /deep/ .el-pager .number {
        min-width: 28px;
        height: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin: 0 4px;
        cursor: pointer;
      }
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  /deep/ .el-table__append-wrapper {
    padding: 10px;
  }

  .el-pagination {
    float: right;
    margin-top: 20px;

    .form-input /deep/ .el-input {
      width: 200px;
    }

    /deep/ .el-input__inner {
      height: 22px;
    }
  }
}
.little-circle {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 3px;
  position: relative;
  right: 6px;
  top: -2px;
  &.red {
    background: #ee5564;
  }
  &.green {
    background: #55c898;
  }
  &.blue {
    background: dodgerblue;
  }
  &.gray {
    background: gray;
  }
}
/deep/ .el-dialog {
  width: 500px;
  border-radius: 5px;
  .el-form-item {
    margin-bottom: 10px;
  }
}

.dialog-inline {
  /deep/ .el-form-item__content {
    width: 300px;
  }

  button.el-button {
    background-color: $--color-primary !important;
    color: #fff !important;
    line-height: 1.2;
  }
}
.visit-cell {
  display: inline-block;
  line-height: 32px;
  // padding-left: 15px;
  // padding-right: 15px;
}
.upload-demo {
  display: inline-block;
}
/deep/.el-table {
  td {
    padding: 16px 0;
    position: relative;
  }
  .el-input {
    &.error {
      .el-input__inner {
        border-color: #ee5564;
      }
    }
  }
  .error-hint {
    position: absolute;
    font-size: 12px;
    color: #ee5564;
    line-height: 14px;
    height: 14px;
    bottom: 1px;
    width: 100%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
</style>
